package com.itita.ww2.handler.requesthandler.worldmap;

import java.sql.SQLException;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSArray;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.enums.UserWMDataFields;
import com.itita.ww2.utils.handler.IRequestOper;

public class ListUserRanking implements IRequestOper {
	private static final int OCCUPIED = 1;
	private static final int DEFENSE = 2;
	private static final int COUNT = 3;

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		int sort = params.getInt("sort"); // 排行类别
		int page = params.getInt("page");
		int pageCount = 50; // 50项
		int uid = UserService.getInstance().getUid(user);
		boolean isEnd = false; // 是否最末页

		int count = UserService.getInstance().getCacheWMUserDataTable().getCount();
		if (count > 0) {
			int curCount = page * pageCount;
			isEnd = curCount >= count;
		}

		ISFSArray ranking = null;
		ISFSObject myself = SFSObject.newInstance();
		switch (sort) {
		case OCCUPIED:
			ranking = UserService.getInstance().getAllUserRanking(UserWMDataFields.BASE_OCCTIMES, page, pageCount);
			myself = UserService.getInstance().getUserRank(uid, UserWMDataFields.BASE_OCCTIMES);
			break;
		case DEFENSE:
			ranking = UserService.getInstance().getAllUserRanking(UserWMDataFields.BASE_DEFTIMES, page, pageCount);
			myself = UserService.getInstance().getUserRank(uid, UserWMDataFields.BASE_DEFTIMES);
			break;
		case COUNT:
			ranking = UserService.getInstance().getAllUserRanking(UserWMDataFields.BASE_COUNT, page, pageCount);
			myself = UserService.getInstance().getUserRank(uid, UserWMDataFields.BASE_DEFTIMES);
			break;
		}

		boolean flag = ranking != null;

		ISFSObject backObj = new SFSObject();
		if (flag) {
			backObj.putBool("isEnd", isEnd);
			backObj.putSFSArray("ranking", ranking);
			backObj.putSFSObject("myself", myself);
		}
		// 回传
		MessageHandler.getInstance().sendMsg(requestCMD, backObj, user, null, flag);
		return true;
	}

}
